package cn.kkcxy.blog.core.exception;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.kkcxy.blog.core.exception.auth.AuthServiceException;
import cn.kkcxy.blog.core.result.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @BelongsProject: kkcxy-blog
 * @BelongsPackage: cn.kkcxy.blog.system.exception
 * @Author: kkcxy
 * @CreateTime: 2024-09-11 23:28
 * @Description: 全局异常处理
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常拦截
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<Object> handleException(Exception e) {
        e.printStackTrace();
        log.error("服务器异常：{}", e.getMessage());
        return ResponseEntity.fail("服务器异常，请联系管理员");
    }

    // 拦截：未登录异常
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> handlerException(NotLoginException e) {
        // 打印堆栈，以供调试
        e.printStackTrace();
        // 返回给前端
        return ResponseEntity.fail("身份验证已失效，请重新登录");
    }

    // 拦截：缺少权限异常
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> handlerException(NotPermissionException e) {
        e.printStackTrace();
        return ResponseEntity.fail("缺少权限：" + e.getPermission());
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> handlerException(NotRoleException e) {
        e.printStackTrace();
        return ResponseEntity.fail("缺少角色：" + e.getRole());
    }

    // 拦截：服务封禁异常
    @ExceptionHandler(DisableServiceException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<String> handlerException(DisableServiceException e) {
        e.printStackTrace();
        return ResponseEntity.fail("当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
    }

    /**
     * Auth 模块异常拦截
     */
    @ExceptionHandler(AuthServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<String> handleAuthException(AuthServiceException e) {
        log.error("服务器异常 [ Auth Module ] 异常信息: {}", e.getMessage());
        return ResponseEntity.fail(e.getMessage());
    }
}
